package com.util.yxy;
import com.bean.yxy.Pagination;
import lombok.Data;
import lombok.ToString;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author 余襄元
 * @date 2023/3/20
 * @projectName 二期项目
 * 分页插件
 **/
@Data
@ToString
public class Page {
    public static Pagination getBynewPageBysum(Integer newPage,Integer onePageSum,String sqlsum,String sql){
        Pagination page = new Pagination();
        Integer sum = Page.getPageSum(sqlsum);
        page.setSum(sum);
        page.setNewPage(newPage);
        page.setOnePageSum(onePageSum);
        Integer pageSum=(int)Math.ceil((double)sum/onePageSum);
        page.setPageSum(pageSum);
        Integer dangqian =(newPage-1)*onePageSum;
        Connection con = Dbutil.getConnection();
        QueryRunner q= new QueryRunner();
        try {
            List<Map<String,Object>> lm=  q.query(con,sql,new MapListHandler(),dangqian,onePageSum);
            page.setLm(lm);
            return page;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Pagination getBynewPageBysum2(Integer newPage,Integer onePageSum,String sqlsum,String sql,String xqid,String name){
        Pagination page = new Pagination();
        Integer sum = Page.getPageSum2(sqlsum,xqid,name);
        page.setSum(sum);
        page.setNewPage(newPage);
        page.setOnePageSum(onePageSum);
        Integer pageSum=(int)Math.ceil((double)sum/onePageSum);
        page.setPageSum(pageSum);
        Integer dangqian =(newPage-1)*onePageSum;
        Connection con = Dbutil.getConnection();
        QueryRunner q= new QueryRunner();
        try {
            List<Map<String,Object>> lm=  q.query(con,sql,new MapListHandler(),xqid,name,dangqian,onePageSum);
            page.setLm(lm);
            return page;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Integer getPageSum2(String sqlsum,String xqid,String name){
        Connection con = Dbutil.getConnection();
        QueryRunner q= new QueryRunner();
        try {
            List<Map<String,Object>> lm=  q.query(con,sqlsum,new MapListHandler(),xqid,name);
            return lm.size();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取总数据
     * @return
     */
    private static Integer getPageSum(String sqlsum){
        Connection con = Dbutil.getConnection();
        QueryRunner q= new QueryRunner();
        try {
            List<Map<String,Object>> lm=  q.query(con,sqlsum,new MapListHandler());
            return lm.size();
       } catch (SQLException e) {
            e.printStackTrace();
       }
        return 0;
    }
}
